package com.wiken.commentservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wiken.commentservice.entity.Like;
import com.wiken.commentservice.service.impl.LikeServiceImpl;
import com.wiken.servicecommon.common.Code;
import com.wiken.servicecommon.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wiken
 * @since 2022-12-28
 */
@RestController
@RequestMapping("/commentservice/like")

public class LikeController {

    @Autowired
    LikeServiceImpl likeService;
    @PostMapping("like")
    public R like(@RequestBody Like like, @RequestHeader("Authorization") String token) {

        //判断是否点过赞，如果没有点过赞就点赞，点过赞就取消点赞

        Map<String, Object> params = new HashMap<>();
        params.put("comment_id", like.getCommentId());
        params.put("user_id", like.getUserId());

        int count = likeService.count(new QueryWrapper<Like>().allEq(params));

        if (count <= 0) {
            boolean success = likeService.like(like, token);

            if (!success) return R.error().code(Code.ERROR).message("点赞失败");

            return R.ok().code(Code.SUCCESS).message("点赞成功");
        }

        boolean success = likeService.cancleLike(like, token);

        if (!success) return R.error().code(Code.ERROR).message("取消点赞成功");

        return R.ok().code(Code.SUCCESS).message("取消点赞失败");
    }

}
